package org.jeecg.modules.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.biz.api.IBizUserApi;
import org.jeecg.biz.entity.BisUser;
import org.jeecg.biz.service.IBisUserService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 业务用户
 * @Author: jeecg-boot
 * @Date: 2025-01-08
 * @Version: V1.0
 */
@Api(tags = "业务用户")
@RestController("AdminBisUserController")
@RequestMapping("/admin/biz/bisUser")
@Slf4j
public class BisUserController extends JeecgController<BisUser, IBisUserService> {
    @Autowired
    private IBisUserService bisUserService;

    /**
     * 分页列表查询
     *
     * @param bisUser
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "业务用户-分页列表查询")
    @ApiOperation(value = "业务用户-分页列表查询", notes = "业务用户-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<BisUser>> queryPageList(BisUser bisUser,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("role", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("sex", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<BisUser> queryWrapper = QueryGenerator.initQueryWrapper(bisUser, req.getParameterMap(), customeRuleMap);
        Page<BisUser> page = new Page<BisUser>(pageNo, pageSize);
        IPage<BisUser> pageList = bisUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param bisUser
     * @return
     */
    @AutoLog(value = "业务用户-添加")
    @ApiOperation(value = "业务用户-添加", notes = "业务用户-添加")
    @RequiresPermissions("biz:bis_user:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody BisUser bisUser) {
        validateUserInfo(bisUser);
        bisUserService.save(bisUser);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param bisUser
     * @return
     */
    @AutoLog(value = "业务用户-编辑")
    @ApiOperation(value = "业务用户-编辑", notes = "业务用户-编辑")
    @RequiresPermissions("biz:bis_user:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody BisUser bisUser) {
        validateUserInfo(bisUser);
        bisUserService.updateById(bisUser);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "业务用户-通过id删除")
    @ApiOperation(value = "业务用户-通过id删除", notes = "业务用户-通过id删除")
    @RequiresPermissions("biz:bis_user:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        bisUserService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "业务用户-批量删除")
    @ApiOperation(value = "业务用户-批量删除", notes = "业务用户-批量删除")
    @RequiresPermissions("biz:bis_user:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.bisUserService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "业务用户-通过id查询")
    @ApiOperation(value = "业务用户-通过id查询", notes = "业务用户-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BisUser> queryById(@RequestParam(name = "id", required = true) String id) {
        BisUser bisUser = bisUserService.getById(id);
        if (bisUser == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(bisUser);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param bisUser
     */
    @RequiresPermissions("biz:bis_user:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BisUser bisUser) {
        return super.exportXls(request, bisUser, BisUser.class, "业务用户");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("biz:bis_user:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BisUser.class);
    }


    /**
     * 编辑
     *
     * @param bisUser
     * @return
     */
    @AutoLog(value = "业务用户-状态修改")
    @ApiOperation(value = "业务用户-状态修改", notes = "业务用户-状态修改")
    @RequiresPermissions("biz:bis_user:edit")
    @RequestMapping(value = "/changeStatus", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> changeStatus(@RequestBody BisUser bisUser) {
        BisUser user = new BisUser();
        user.setId(bisUser.getId());
        user.setStatus(bisUser.getStatus());
        bisUserService.updateById(user);
        return Result.OK("状态修改成功!");
    }


    /**
     * 密码重置
     */
    @AutoLog(value = "业务用户-密码重置")
    @ApiOperation(value = "业务用户-密码重置", notes = "业务用户-密码重置")
    @RequiresPermissions("biz:bis_user:edit")
    @RequestMapping(value = "/resetPassword", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> resetPassword(@RequestBody BisUser bisUser) {
        BisUser user = bisUserService.getById(bisUser);
        String initPassword = "123456";  // 初始密码
        String salt = oConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), initPassword, salt);
        user.setPassword(passwordEncode);
        user.setSalt(salt);

        // 只更新密码
        BisUser newUser = new BisUser();
        newUser.setId(user.getId());
        newUser.setPassword(passwordEncode);
        newUser.setSalt(salt);
        bisUserService.updateById(newUser);
        return Result.OK("状态修改成功!");
    }

    /**
     * 校验用户
     * @param bisUser
     */
    private void validateUserInfo(BisUser bisUser) {
        long countByUsername = bisUserService.count(new LambdaQueryWrapper<BisUser>().eq(BisUser::getUsername, bisUser.getUsername()));
        if (countByUsername > 0) {
            throw new JeecgBootException("用户名重复！");
        }
        long countByPhone = bisUserService.count(new LambdaQueryWrapper<BisUser>().eq(BisUser::getPhone, bisUser.getPhone()));
        if (countByPhone > 0) {
            throw new JeecgBootException("手机号重复!");
        }
        long countByEmail = bisUserService.count(new LambdaQueryWrapper<BisUser>().eq(BisUser::getEmail, bisUser.getEmail()));
        if (countByEmail > 0) {
            throw new JeecgBootException("邮箱重复！");
        }
    }
}
